<!-- src/layouts/SidebarItem.vue -->
<template>
  <el-menu-item
    v-if="!hasChildren"
    :index="resolvePath"
    @click="handleClick"
  >
    <el-icon v-if="route.meta?.icon">
      <component :is="iconComponent" />
    </el-icon>
    <span>{{ route.meta?.title }}</span>
  </el-menu-item>

  <el-sub-menu v-else :index="resolvePath">
    <template #title>
      <el-icon v-if="route.meta?.icon">
        <component :is="iconComponent" />
      </el-icon>
      <span>{{ route.meta?.title }}</span>
    </template>
    <sidebar-item
      v-for="child in route.children"
      :key="child.path"
      :route="child"
      :base-path="resolvePath"
    />
  </el-sub-menu>
</template>

<script setup>
import { computed } from "vue";
import { useRouter } from "vue-router";
import {
  HomeFilled,
  DataLine,
  User,
  Setting,
  Document,
  Folder,
} from "@element-plus/icons-vue";

const props = defineProps({
  route: {
    type: Object,
    required: true,
  },
  basePath: {
    type: String,
    default: "",
  },
});

const router = useRouter();

// 图标映射
const iconMap = {
  home: HomeFilled,
  dashboard: DataLine,
  user: User,
  setting: Setting,
  document: Document,
  folder: Folder,
};

const iconComponent = computed(() => {
  const iconName = props.route.meta?.icon;
  return iconMap[iconName] || Document;
});

const hasChildren = computed(() => {
  return props.route.children && props.route.children.length > 0;
});

const resolvePath = computed(() => {
  // 如果路径已经是绝对路径，直接返回
  if (props.route.path.startsWith("/")) {
    return props.route.path;
  }
  
  // 如果没有 basePath，添加根路径
  if (!props.basePath || props.basePath === "") {
    return `/${props.route.path}`;
  }
  
  // 拼接 basePath 和路径，去除多余的斜杠
  return `${props.basePath}/${props.route.path}`.replace(/\/+/g, "/");
});

const handleClick = () => {
  router.push(resolvePath.value);
};
</script>

<style scoped>
/* 图标样式在父组件 Sidebar.vue 中统一处理 */
</style>
